package org.example.service.serviceImpl;

import org.example.exception.ExamException;
import org.example.model.Enum.ExamType;
import org.example.model.ExamDatabase;
import org.example.model.PoJo.ExamData;
import org.example.model.PoJo.OneData;
import org.example.model.PoJo.StudentAnswer;
import org.example.service.ExamSystem;

import java.time.LocalDateTime;
import java.util.*;

public class ExamSystemImpl implements ExamSystem {
    /**
     * 加载考试题目
     * @param examType
     * @return
     */
    @Override
    public ExamData initExam(ExamType examType) {
        if (!isExamSubject(examType)){
            throw new ExamException("无效科目");
        }

        ExamDatabase.init();

        List<ExamData> list = ExamDatabase.getExamDataList(examType);
        if (list == null || list.size() == 0){
            throw new ExamException("试题不足");
        }

        Random random = new Random();
        ExamData examData = list.get(random.nextInt(list.size()));

        return examData;
    }

    /**
     * 开始考试
     * @param examData
     */
    @Override
    public StudentAnswer startExam(ExamData examData) {
        //开始计时
        startTime();

        List<OneData> oneDataList = examData.getOneDataList();



        Scanner sc = new Scanner(System.in);
        StudentAnswer answerList = new StudentAnswer();
        for (int i = 0; i < oneDataList.size(); i++) {
            System.out.println("第" + (i + 1) + "题:" + oneDataList.get(i).getTitle() + "  (十分)");
            String studentAnswer = sc.nextLine();
            if (studentAnswer.equals("交卷")){
                return answerList;
            }
            answerList.getStudentAnswersList().add(studentAnswer);
        }
        return answerList;
    }

    @Override
    public Integer score(StudentAnswer studentAnswer, ExamData examData) {
        List<String> studentAnswersList = studentAnswer.getStudentAnswersList();
        List<OneData> answersList = examData.getOneDataList();

        int score = 0;
        for (int i = 0; i < studentAnswersList.size(); i++) {
            if (studentAnswersList.get(i).equals(answersList.get(i).getAnswer())){
                score = score + 10;
            }
        }
        return score;
    }

    private void startTime(){
        //开始120分钟倒计时
        final int[] time = {60};
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                time[0] = time[0] - 1;
                if (time[0] == 0){
                    System.out.println(time[0]);
                    System.exit(0);
                }
            }
        },0,1000);
    }


    private boolean isExamSubject(ExamType examType) {
        for (ExamType type : ExamType.values()) {
            if (type.equals(examType)){
                return true;
            }
        }
        return false;
    }
}
